package com.example.test

import android.content.Intent
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugins.ToastPlugin

const val REQUEST_CODE_NOTIFICATION_SETTINGS = 1000
const val APP_NOTIFICATION_CHANNEL = "com.yichip.watch/notification_channel"

class MainActivity: FlutterActivity() {
    private var notificationListener: NotificationListener? = null
    companion object {
        var eventConsumer: EventChannel.EventSink? = null
    }
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        // 注册自定义插件
        flutterEngine.plugins.add(ToastPlugin(this));
        // 注册通知栏事件监听
        EventChannel(flutterEngine.dartExecutor.binaryMessenger, APP_NOTIFICATION_CHANNEL).setStreamHandler(
            object : EventChannel.StreamHandler {

                override fun onListen(arguments: Any?, eventCallback: EventChannel.EventSink) {
                    eventConsumer = eventCallback
                    // 判断通知使用权权限是否已启用
                    if (!isNotificationListenerEnabled()) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                            startNotificationSetting()
                        } else {
                            eventCallback.error("", "缺少通知使用权权限", "手机版本太低")
                        }
                        return
                    }
                    println("开始监听消息通知")
                    startListening()
                }

                override fun onCancel(arguments: Any?) {
                    println("停止监听消息通知")
                    stopListening()
                }
            }
        )
    }

    private fun startListening() {
        // 创建通知监听服务
        notificationListener = NotificationListener()
        // 设置回调
        notificationListener?.setEventCallback(eventConsumer!!)
        // 开启监听
        notificationListener?.startListening(applicationContext)
    }

    private fun stopListening() {
        notificationListener?.stopListening(applicationContext)
        notificationListener = null
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_NOTIFICATION_SETTINGS) {
            val isPermissionGranted = isNotificationListenerEnabled()
            if (isPermissionGranted) {
                startListening()
            }
        }
    }

    /**
     * 判断应用是否有权限
     */
    private fun isNotificationListenerEnabled(): Boolean {
        var enable = false
        val packageName = packageName
        val flat: String? =
            Settings.Secure.getString(contentResolver, "enabled_notification_listeners")
        if (flat != null) {
            enable = flat.contains(packageName)
        }
        return enable
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    private fun startNotificationSetting() {
        startActivityForResult(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS), REQUEST_CODE_NOTIFICATION_SETTINGS);
    }
}
